package com.flyqiu.form.core.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flyqiu.form.api.service.FlyQiuTableConfigService;
import com.flyqiu.form.common.exceptions.FlyQiuFormException;
import com.flyqiu.form.mapper.FlyQiuTableConfigMapper;
import com.flyqiu.form.model.entity.FlyQiuTableConfig;
import org.apache.commons.lang3.StringUtils;


public class FlyQiuTableConfigServiceImpl extends ServiceImpl<FlyQiuTableConfigMapper, FlyQiuTableConfig> implements FlyQiuTableConfigService {


    public FlyQiuTableConfigServiceImpl(FlyQiuTableConfigMapper mapper) {
        this.baseMapper = mapper;
    }

    @Override
    public boolean save(FlyQiuTableConfig entity) {
        if (StringUtils.isEmpty(entity.getTableName())) throw new FlyQiuFormException("数据表名不能为空");
        if (StringUtils.isEmpty(entity.getFormName())) throw new FlyQiuFormException("数据表中文名称不能为空");
        if (StringUtils.isAllBlank(entity.getTenantId())) {
            entity.setTenantId("admin");
        }
        return super.save(entity);
    }


    @Override
    public boolean updateById(FlyQiuTableConfig entity) {

        return super.updateById(entity);
    }

    /**
     * 根据表单编码获取表单配置
     *
     * @param formCode 表单编码
     * @return 表单配置
     */
    @Override
    public FlyQiuTableConfig getOneByFormCode(String formCode) {
        LambdaQueryWrapper<FlyQiuTableConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FlyQiuTableConfig::getFormCode, formCode);
        return getOne(queryWrapper);
    }


    @Override
    public long getTableHistoryCount(String tableName) {
        LambdaQueryWrapper<FlyQiuTableConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FlyQiuTableConfig::getTableName, tableName);
        queryWrapper.gt(FlyQiuTableConfig::getTableVersion, 0);
        return count(queryWrapper);
    }
}
